// src/router/index.js (或者你的路由配置文件，例如 src/router.js)

import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '../stores/user'; // 确保路径正确

// 布局 (Layouts)
import AuthLayout from '@/layouts/AuthLayout.vue';
import ClientLayout from '@/layouts/ClientLayout.vue';
import EmployeeLayout from '@/layouts/EmployeeLayout.vue';
import AdminLayout from '@/layouts/AdminLayout.vue';
// 公共视图 (Common Views)
import LoginPage from '@/views/common/LoginPage.vue';
import RegisterPage from '@/views/common/RegisterPage.vue';
import NotFoundPage from '@/views/common/NotFoundPage.vue';
import UnauthorizedPage from '@/views/common/UnauthorizedPage.vue';
// 客户视图 (Client Views)
import ClientDashboard from '@/views/client/ClientDashboard.vue';
import MakeBookingPage from '@/views/client/MakeBookingPage.vue';
import MyBookingsPage from '@/views/client/MyBookingsPage.vue';
import BookingDetailsPage from '@/views/client/BookingDetailsPage.vue';
import CancelBookingPage from '@/views/client/CancelBookingPage.vue';
import ClientProfilePage from '@/views/client/ClientProfilePage.vue';
// 员工视图 (Employee Views)
import EmployeeDashboard from '@/views/employee/EmployeeDashboard.vue';
import AllRoomsCurrentStatusPage from '@/views/employee/AllRoomsCurrentStatusPage.vue';
import SingleRoomTimelinePage from '@/views/employee/SingleRoomTimelinePage.vue';
import BookingManagementPage from '@/views/employee/BookingManagementPage.vue';
import CancellationApprovalPage from '@/views/employee/CancellationApprovalPage.vue';
import MaintenanceManagementPage from '@/views/employee/MaintenanceManagementPage.vue';
import EmployeeProfilePage from '@/views/employee/EmployeeProfilePage.vue';
// 管理员视图 (Admin Views)
import AdminDashboard from '@/views/admin/AdminDashboard.vue';
import MeetingRoomManagementPage from '@/views/admin/MeetingRoomManagementPage.vue';
import UserManagementPage from '@/views/admin/UserManagementPage.vue';
import AdminProfilePage from '@/views/admin/AdminProfilePage.vue';

// 辅助函数，用于在路由守卫中获取用户角色
// (这里直接使用 store 的 getter 更佳，在 beforeEach 中直接调用)

// 辅助函数：检查用户是否已认证 (可选，因为主要逻辑在 beforeEach 中)
// 如果你仍然在 beforeEnter 中使用它，确保它能利用更新后的 store
const isUserAuthenticated = () => {
  const userStore = useUserStore();
  // 如果 store 中未认证，尝试从 localStorage 恢复
  // 这确保了即使在组件或 beforeEnter 中首次调用时也能尝试恢复
  if (!userStore.isAuthenticated) {
    userStore.checkAuth();
  }
  return userStore.isAuthenticated;
};

// 辅助函数：获取用户角色 (可选，因为主要逻辑在 beforeEach 中使用 getter)
const getCurrentUserRole = () => {
  const userStore = useUserStore();
  // 确保 checkAuth 已经被调用（例如通过 isUserAuthenticated 或 beforeEach）
  return userStore.getUserRoleForGuard; // 使用 store 中的 getter
};


const routes = [
  // 公共路由 (登录、注册)
  {
    path: '/',
    component: AuthLayout,
    children: [
      { path: '', redirect: '/login' },
      { path: 'login', name: 'Login', component: LoginPage, meta: { title: '登录' } },
      { path: 'register', name: 'Register', component: RegisterPage, meta: { title: '客户注册' } },
    ],
  },
  // 客户路由
  {
    path: '/client',
    component: ClientLayout,
    meta: { requiresAuth: true, roles: ['client'], title: '客户中心' },
    // beforeEnter 守卫现在可以依赖 beforeEach 中更新的状态，或者按需保留
    beforeEnter: (to, from, next) => {
      if (!isUserAuthenticated()) { // isUserAuthenticated 内部会调用 checkAuth
        next({ name: 'Login', query: { redirect: to.fullPath } });
      } else if (!to.meta.roles.includes(getCurrentUserRole())) {
        next({ name: 'Unauthorized' });
      } else {
        next();
      }
    },
    children: [
      { path: '', redirect: { name: 'ClientDashboard' } },
      { path: 'dashboard', name: 'ClientDashboard', component: ClientDashboard, meta: { title: '客户仪表盘' } },
      { path: 'book', name: 'MakeBooking', component: MakeBookingPage, meta: { title: '预订会议室' } },
      { path: 'bookings', name: 'MyBookings', component: MyBookingsPage, meta: { title: '我的预订' } },
      { path: 'bookings/:id', name: 'BookingDetails', component: BookingDetailsPage, props: true, meta: { title: '预订详情' } },
      { path: 'cancel-booking', name: 'CancelBooking', component: CancelBookingPage, meta: { title: '取消预订' } },
      { path: 'profile', name: 'ClientProfile', component: ClientProfilePage, meta: { title: '个人资料' } },
    ],
  },
  // 员工路由
  {
    path: '/employee',
    component: EmployeeLayout,
    meta: { requiresAuth: true, roles: ['employee'], title: '员工工作台' },
    beforeEnter: (to, from, next) => {
      if (!isUserAuthenticated()) {
        next({ name: 'Login', query: { redirect: to.fullPath } });
      } else if (!to.meta.roles.includes(getCurrentUserRole())) {
        next({ name: 'Unauthorized' });
      } else {
        next();
      }
    },
    children: [
      { path: '', redirect: { name: 'EmployeeDashboard' } },
      { path: 'dashboard', name: 'EmployeeDashboard', component: EmployeeDashboard, meta: { title: '员工仪表盘' } },
      { path: 'room-status', name: 'AllRoomsCurrentStatus', component: AllRoomsCurrentStatusPage, meta: { title: '会议室即时状态' } },
      { path: 'room-timeline/:roomId', name: 'SingleRoomTimeline', component: SingleRoomTimelinePage, props: true, meta: { title: '会议室详细时间表' } },
      { path: 'booking-management', name: 'BookingManagement', component: BookingManagementPage, meta: { title: '预订管理与状态更新' } },
      { path: 'cancellation-approval', name: 'CancellationApprovals', component: CancellationApprovalPage, meta: { title: '取消申请审批' } },
      { path: 'maintenance-management', name: 'MaintenanceManagement', component: MaintenanceManagementPage, meta: { title: '维修管理' } },
      { path: 'profile', name: 'EmployeeProfile', component: EmployeeProfilePage, meta: { title: '个人资料' } },
    ],
  },
  // 管理员路由
  {
    path: '/admin',
    component: AdminLayout,
    meta: { requiresAuth: true, roles: ['admin'], title: '管理后台' },
    beforeEnter: (to, from, next) => {
      if (!isUserAuthenticated()) {
        next({ name: 'Login', query: { redirect: to.fullPath } });
      } else if (!to.meta.roles.includes(getCurrentUserRole())) {
        next({ name: 'Unauthorized' });
      } else {
        next();
      }
    },
    children: [
      { path: '', redirect: { name: 'AdminDashboard' } },
      { path: 'dashboard', name: 'AdminDashboard', component: AdminDashboard, meta: { title: '管理员仪表盘' } },
      { path: 'rooms', name: 'MeetingRoomManagement', component: MeetingRoomManagementPage, meta: { title: '会议室管理' } },
      { path: 'users', name: 'UserManagement', component: UserManagementPage, meta: { title: '用户管理' } },
      { path: 'profile', name: 'AdminProfile', component: AdminProfilePage, meta: { title: '个人资料' } },
    ],
  },
  // 辅助路由
  { path: '/unauthorized', name: 'Unauthorized', component: UnauthorizedPage, meta: { title: '无权限访问' } },
  { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFoundPage, meta: { title: '页面未找到' } },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL || '/'),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { top: 0, behavior: 'smooth' };
    }
  }
});

router.beforeEach((to, from, next) => {
  const baseTitle = '会议室预订系统';
  document.title = to.meta.title ? `${to.meta.title} - ${baseTitle}` : baseTitle;

  const userStore = useUserStore();

  // 关键：在每次导航前，如果 store 中用户未认证，则尝试从 localStorage 恢复状态
  // 这一步会调用更新后的 checkAuth，它会尝试解码 token 并恢复 user 对象和角色
  if (!userStore.isAuthenticated) {
    userStore.checkAuth();
  }

  // console.log(`Navigating to: ${to.path}`);
  // console.log(`User authenticated (in beforeEach): ${userStore.isAuthenticated}`);
  // console.log(`User role (in beforeEach): ${userStore.getUserRoleForGuard}`);

  const requiresAuth = to.meta.requiresAuth;
  const requiredRoles = to.meta.roles;

  if (requiresAuth) {
    if (!userStore.isAuthenticated) {
      // console.log('Redirecting to Login: User not authenticated.');
      next({
        name: 'Login',
        query: { redirect: to.fullPath } // 保存用户想要访问的路径
      });
      return; // 必须 return，确保 next() 只被调用一次
    }

    // 用户已认证，现在检查角色权限
    const currentUserRole = userStore.getUserRoleForGuard; // 使用 getter
    if (requiredRoles && Array.isArray(requiredRoles) && requiredRoles.length > 0) {
      if (!currentUserRole || !requiredRoles.includes(currentUserRole)) {
        // console.log(`Redirecting to Unauthorized: Role mismatch. Required: ${requiredRoles}, User has: ${currentUserRole}`);
        next({ name: 'Unauthorized' });
        return; // 必须 return
      }
    }
  }

  // 处理已登录用户访问登录/注册页面的情况 (可选)
  if ((to.name === 'Login' || to.name === 'Register') && userStore.isAuthenticated) {
    // console.log('User is authenticated and trying to access Login/Register. Redirecting...');
    // 根据角色重定向到各自的仪表盘
    const role = userStore.getUserRoleForGuard;
    if (role === 'client') {
      next({ name: 'ClientDashboard' });
    } else if (role === 'employee') {
      next({ name: 'EmployeeDashboard' });
    } else if (role === 'admin') {
      next({ name: 'AdminDashboard' });
    } else {
      next('/'); // 未知角色或默认跳转
    }
    return; // 必须 return
  }

  next(); // 所有检查通过，或路由不需要认证
});

export default router;